var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var jwt = require("jsonwebtoken")
var positionsRouter = require('./routes/positions');
var users = require('./routes/users')
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//设置允许跨域
// app.all('*', function (req, res, next) {
//   res.header("Access-Control-Allow-Credentials", "true")
//   res.header("Access-Control-Allow-Origin", "*")
//   res.header("Access-Control-Allow-Headers", "*");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By", ' 3.2.1')
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next();
// });
//positions路由

const Authorization = (req, res, next) => {
  console.log(req.path)
  let token = req.body.token || req.query.token || req.headers['authoration']
  console.log(req.headers)
  console.log(token)
  let sercrect = 'MY_NAME_IS_HMM';
  if (req.path === '/users/login' || req.path === '/users/register') {
    next()
  } else {
    jwt.verify(token, sercrect, (err, decode) => {
      if (err) {
        res.send({ status: 304, msg: "无效的验证" })
      } else {
        if (req.path !== "/users/check") {
          next()
        } else {
          res.send({ status: 200, msg: "验证成功", username: decode.username })
        }
      }
    })
  }
}

app.use('/', Authorization)
app.use('/positions', positionsRouter);
app.use('/users', users)
module.exports = app;
